#!/bin/env python

import os
import re
import sys


def _patchAnchor(filename):
    content = ''
    with file(filename, 'rb') as f:
        content = f.read()

    fix = ''
    left = content
    while left != '':
        m = re.match(
            r'[\s\S]*?<(div|h1|h2|h3|h4|span)\s+.*?id='
            r'"(?P<id>[A-Za-z0-9_\-]+)"\s*>(?P<left>[\s\S]*)$', left)

        if m is not None:
            mpos = m.start('left')
            fix += left[:mpos] + '<a name="%s"></a>' % m.group('id')
            left = m.group('left')
        else:
            fix += left
            left = ''

    if content != fix:
        print 'Update %s' % filename
        with file(filename, 'wb') as f:
            f.write(fix)

if __name__ == '__main__':
    path = sys.argv[1] if len(sys.argv) > 1 else os.getcwd()

    for root, _, files in os.walk(path):
        for f in files:
            if f.endswith('.htm') or f.endswith('.html'):
                _patchAnchor(os.path.join(root, f))
